package com.kaowen.spider;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * 数据库全文搜索
 * 
 * @author thinkpad
 */
public class 全文检索 {

	private static Logger logger = Logger.getLogger(全文检索.class);

	static {
		try {
			// 加载MySql的驱动类
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("找不到驱动程序类 ，加载驱动失败！");
			e.printStackTrace();
		}
	}

	public void search(String conditionSql, String colDataType,
			boolean firstResultExit) throws Exception {
		String url = "jdbc:oracle:thin:@7.107.82.103:1521:orcl";
		String username = "bladelogic";
		String password = "sa";
		Connection conn = DriverManager.getConnection(url, username, password);

		String sql = "select t.TABLE_NAME,t.COLUMN_NAME from user_tab_columns t where t.DATA_TYPE = ?";
		PreparedStatement stm = conn.prepareStatement(sql);
		stm.setString(1, colDataType);
		ResultSet rs = stm.executeQuery();
		List<String> sqlList = new ArrayList<String>();
		while (rs.next()) {
			String tableName = rs.getString(1);
			String colName = rs.getString(2);
			sqlList.add("select count(1) from " + tableName + " where "
					+ colName + " ");
		}
		rs.close();
		stm.close();

		for (int i = 0; i < sqlList.size(); i++) {
			stm = conn.prepareStatement(sqlList.get(i) + conditionSql);
			rs = stm.executeQuery();
			rs.next();
			if (rs.getBigDecimal(1).intValue() > 0) {
				logger.info((sqlList.get(i) + conditionSql+"\t--搜索到结果:"+rs.getBigDecimal(1).intValue()).replace("count(1)", "*"));
				if (firstResultExit) {
					break;
				}
			}
			rs.close();
			stm.close();
		}

		conn.close();
	}

	public static void main(String[] args) {
		全文检索 spider = new 全文检索();
		try {
			//spider.search(" like '%bladelogic-2%'", "NVARCHAR2", false);
			spider.search("= 2000300", "NUMBER", false);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
